﻿/*----------------------------------------------------------------
    // Copyright (C) 2009 江苏华招网
    // 版权所有。 
    // 作者：庄金冬 
    //
    // 文件名：BLL_Company.cs
    // 文件功能描述：企业操作业务逻辑类,,实现接口IBLL_Company,继承自类MarshalByRefObject
    // 创建标识：庄金冬2009-03-06
    //
    // 修改标识：
    // 修改描述：
    //
    // 修改标识：
    // 修改描述：
    //
    // 审核人：
    // 审核时间：
    // 审核说明：
 //----------------------------------------------------------------*/
using System;
using System.Collections.Generic;

using System.Text;
using HZ.DrugTrade.IBLL;
using HZ.DrugTrade.Model;
using HZ.DrugTrade.DAL;
using System.Data;
namespace HZ.DrugTrade.BLL
{
    using HZ.Common;

    [Serializable]
    /// <summary>
    /// 企业操作业务逻辑类,实现接口IBLL_Company,继承自类MarshalByRefObject
    /// </summary>
    public class BLL_Company : MarshalByRefObject, IBLL_Company
    {
        #region IBLL_Company 成员

        /// <summary>
        /// 获取所有企业
        /// </summary>
        /// <returns>所有企业</returns>
        public IList<Company> GetAllCompany()
        {
            BLL_UserSession.CheckSession();
            return DAL_Company.GetAllCompany();
        }
        /// <summary>
        /// 获取配送企业数量
        /// </summary>
        /// <returns>数量</returns>
        public int GetAllCompanyCount()
        {
            return DAL_Company.GetAllCompanyCount();
        }

        /// <summary>
        ///  获取生产企业最大编号    add by tzh
        /// </summary>
        /// <param name="ComInfo"></param>
        /// <returns></returns>
        public string GetCompanySID()
        {
            BLL_UserSession.CheckSession();
            return DAL_Company.GetCompanySID();
        }
        /// <summary>
        /// 获取经营企业最大编号    add by tzh
        /// </summary>
        /// <returns></returns>
        public string GetCompanyJID()
        {
            BLL_UserSession.CheckSession();
            return DAL_Company.GetCompanyJID();
        }
        /// <summary>
        /// 获取配送企业最大编号    add by tzh
        /// </summary>
        /// <returns></returns>
        public string GetCompanyPID()
        {
            BLL_UserSession.CheckSession();
            return DAL_Company.GetCompanyPID();
        }
        /// <summary>
        /// 编辑企业
        /// </summary>
        /// <param name="company">企业</param>
        /// <returns>True:成功;False:失败</returns>
        public bool UpdateCompany(Company company)
        {
            BLL_UserSession.CheckSession();
            bool state = DAL_Company.UpdateCompany(company);
            if(state == true)
            {
                BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog { OperateMessage = string.Format("编辑企业：{0};处理时间:{1};)", company.CompanyID, DateTime.Now.ToString()), ClientIP = HZ.Fun2.GetClientIP() });
            }
            return state;
        }
        /// <summary>
        /// 编辑企业
        /// </summary>
        /// <param name="company">企业</param>
        /// <returns>True:成功;False:失败</returns>
        public int UpdateCompany2(Company company)
        {
            BLL_UserSession.CheckSession();
            int state = DAL_Company.UpdateCompany2(company);
            if(state == 1)
            {
                BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog { OperateMessage = string.Format("编辑企业：{0};处理时间:{1};)", company.CompanyID, DateTime.Now.ToString()), ClientIP = HZ.Fun2.GetClientIP() });
            }
            return state;
        }

        /// <summary>
        /// 删除企业
        /// </summary>
        /// <param name="company">企业</param>
        /// <returns>0.删除失败;1.删除成功;2.已被使用不能删除;</returns>
        public int DeleteCompany(Company company)
        {
            BLL_UserSession.CheckSession();
            int state = DAL_Company.DeleteCompany(company);
            if(state == 1)
            {
                BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog { OperateMessage = string.Format("删除企业：{0};处理时间:{1};)", company.CompanyID, DateTime.Now.ToString()), ClientIP = HZ.Fun2.GetClientIP() });
            }
            return state;
        }

        /// <summary>
        /// 添加企业
        /// </summary>
        /// <param name="company">企业</param>
        /// <returns>0.添加失败;1.添加成功;2.已经存在;</returns>
        public int AddCompany(Company company)
        {

            BLL_UserSession.CheckSession();
            int state = DAL_Company.AddCompany(company);
            if(state == 1)
            {
                BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog { OperateMessage = string.Format("添加企业：{0};处理时间:{1};)", company.CompanyID, DateTime.Now.ToString()), ClientIP = HZ.Fun2.GetClientIP() });
            }
            return state;
        }

        /// <summary>
        /// 获取所有未注册企业
        /// </summary>
        /// <returns>所有未注册企业</returns>
        public IList<Company> GetAllUnregCompany()
        {

            BLL_UserSession.CheckSession();
            return DAL_Company.GetAllUnregCompany();
        }

        /// <summary>
        /// 获取所有未注册企业
        /// </summary>
        /// <param name="blSc">是否为生产:true，生产企业；false，其它</param>
        /// <returns>所有未注册企业</returns>
        public IList<Company> GetAllUnregCompany(bool blSc)
        {

            BLL_UserSession.CheckSession();
            return DAL_Company.GetAllUnregCompany(blSc);
        }
        /// <summary>
        /// 条件企业查询
        /// </summary>
        /// <param name="company">查询用实体</param>
        /// <param name="currentPage">当前页</param>
        /// <param name="pageSize">每页显示记录数</param>
        /// <param name="totalRecord">（输出参数）总记录数目</param>
        /// <returns></returns>
        public IList<Company> GetCompanyByWhere(HZ.DrugTrade.Model.Query.Company company, int currentPage, int pageSize, out int totalRecord)
        {

            BLL_UserSession.CheckSession();
            return DAL_Company.GetCompanyByWhere(company, currentPage, pageSize, out totalRecord);
        }

        /// <summary>
        /// 条件企业查询
        /// </summary>
        /// <param name="company">查询用实体</param>
        /// <param name="currentPage">当前页</param>
        /// <param name="pageSize">每页显示记录数</param>
        /// <param name="totalRecord">（输出参数）总记录数目</param>
        /// <returns></returns>
        public IList<Company> GetCompanyByCondition(HZ.DrugTrade.Model.Query.Company company, int currentPage, int pageSize, out int totalRecord)
        {
            BLL_UserSession.CheckSession();
            return DAL_Company.GetCompanyByCondition(company, currentPage, pageSize, out totalRecord);
        }

        /// <summary>
        /// 条件企业查询
        /// </summary>
        /// <param name="company">查询用实体</param>
        /// <param name="currentPage">当前页</param>
        /// <param name="pageSize">每页显示记录数</param>
        /// <param name="totalRecord">（输出参数）总记录数目</param>
        /// <returns></returns>
        public IList<Company> GetCompanyByCondition_PS(HZ.DrugTrade.Model.Query.Company company, int currentPage, int pageSize, out int totalRecord)
        {
            BLL_UserSession.CheckSession();
            return DAL_Company.GetCompanyByCondition_PS(company, currentPage, pageSize, out totalRecord);
        }

        /// <summary>
        /// 条件企业查询
        /// </summary>
        /// <param name="company">查询用实体</param>
        /// <param name="currentPage">当前页</param>
        /// <param name="pageSize">每页显示记录数</param>
        /// <param name="totalRecord">（输出参数）总记录数目</param>
        /// <returns></returns>
        public DataTable GetCompanyInfoByWhere(HZ.DrugTrade.Model.Query.Company company, int currentPage, int pageSize, out int totalRecord)
        {

            BLL_UserSession.CheckSession();
            return DAL_Company.GetCompanyInfoByWhere(company, currentPage, pageSize, out totalRecord);
        }
        /// <summary>
        /// 自助注册一个新企业信息
        /// </summary>
        /// <param name="companyinfo"></param>
        /// <returns></returns>
        public int RegNewCompany(Model.CompanyInfo companyinfo)
        {
            //int i = 0;
            //try
            //{
            //    //return HZ.Data.DAL_Helper.OperateTableSQL(companyinfo, HZ.Data.TableOperator.Insert);     //update by lhl 2009-08-28
            //    i = HZ.Data.DAL_Helper.OperateTableSQL(companyinfo, HZ.Data.TableOperator.Insert);
            //    if (i == 1)
            //    {
            //        BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog { OperateMessage = string.Format("添加企业成功(企业名称：{0})", companyinfo.CompanyName) });

            //    }
            //}
            //catch (System.Data.SqlClient.SqlException ee)
            //{

            //    log4netManager.LogDebug("BLL_Company", "出现SqlException", ee);
            //    //return 2;
            //    i = 2;
            //}
            //return i;
            int state = DAL_Company.RegNewCompany(companyinfo);
            if(state == 1)
            {
                BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog { OperateMessage = string.Format("自助注册一个新企业信息：{0};处理时间:{1};)", companyinfo.CompanyID, DateTime.Now.ToString()), ClientIP = HZ.Fun2.GetClientIP() });
            }
            return state;


        }

        /// <summary>
        /// 自助注册一个新企业信息 add by zdc
        /// </summary>
        /// <param name="companyinfo"></param>
        /// <returns></returns>
        public int RegNewCompany(Model.CompanyInfo companyinfo, string comType)
        {
            int state = DAL_Company.RegNewCompany(companyinfo, comType);
            if(state == 1)
            {
                BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog { OperateMessage = string.Format("自助注册一个新企业信息：{0};处理时间:{1};)", companyinfo.CompanyID, DateTime.Now.ToString()), ClientIP = HZ.Fun2.GetClientIP() });
            }
            return state;
            //int i = 0;
            //try
            //{
            //    //return DAL.DAL_Helper.OperateTableSQL(companyinfo, TableOperator.Add);     //update by lhl 2009-08-28
            //    i = DAL.DAL_Helper.OperateTableSQL(companyinfo, TableOperator.Add);
            //    if (i == 1)
            //    {
            //        BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog { OperateMessage = string.Format("添加企业成功(企业名称：{0})", companyinfo.CompanyName) });

            //    }
            //}
            //catch (System.Data.SqlClient.SqlException ee)
            //{

            //    log4netManager.LogDebug("BLL_Company", "出现SqlException", ee);
            //    //return 2;
            //    i = 2;
            //}
            //return i;
            //            HZ.Data.SQLHelper sh = new HZ.Data.SQLHelper();
            //            StringBuilder sb = new StringBuilder();
            //            try
            //            {
            //                sh.BeginTrans(); //锁定表
            //                // 插入医疗机构
            //                // 获取最大的UserID
            //                System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"\d+");
            //                string sql = @"if exists(SELECT UserID FROM TB_USER WHERE UserID='" + companyinfo.CompanyID + @"') Select 1 
            //                             Else if exists(select CompanyName from Tb_company where CompanyName like '%" + companyinfo.CompanyName + "%') Select 2 else Select 0";
            //                object obj = sh.ExecuteScalar(sql);
            //                string maxid = string.Empty;
            //                int id = 0;
            //                if (obj.ToString() == "1" || obj.ToString() == "2")
            //                {
            //                    sh.RollTrans();
            //                    return 2;
            //                }
            //                sb.Append(" Insert Into TB_User (UserID,UserName,Userpassword,isadmin,isUsing) values('" + companyinfo.CompanyID + "','" + companyinfo.CompanyName + "', '123456',1,0);");
            //                string CompanyType = "";

            //                if (companyinfo.CompanyID.ToLower().StartsWith("p"))
            //                    CompanyType = "2";
            //                else if (companyinfo.CompanyID.ToLower().StartsWith("j"))
            //                    CompanyType = "1";
            //                else if (companyinfo.CompanyID.ToLower().StartsWith("s"))
            //                    CompanyType = "0";
            //                else
            //                {
            //                    sh.RollTrans();
            //                    return 2;
            //                }
            //                sb.Append(" Insert Into TB_Company Select '" + companyinfo.CompanyID + "','" + companyinfo.CompanyName + "'," + comType + ",'';");
            //                sb.Append(" Insert Into Tb_Role_User Select '" + companyinfo.CompanyID + "','" + (CompanyType == "2" ? "02" : "05") + "',1,'" + companyinfo.CompanyID + "'; ");
            //                sb.Append(HZ.Data.DAL_Helper.GetInsertSql(companyinfo));


            //                sh.ExecuteNonQuery(sb.ToString());
            //                // 插入医疗机构帐号关联
            //                // 插入帐号权限
            //                sh.CommitTrans();
            //                return 1;
            //            }
            //            catch (Exception ee)
            //            {
            //                sh.RollTrans();
            //                throw ee;
            //                return 0;
            //            }
        }

        /// <summary>
        /// 投标企业注册一个新配送企业信息
        /// </summary>
        /// <param name="companyinfo"></param>
        /// <returns></returns>
        public int RegNewCompany(Model.CompanyInfo companyinfo, Model.SelectArea selectArea)
        {
            int result = 0;
            var sh = HZ.Data.DbHelperFactory.Create();
            string outUserIDs = "";
            try
            {
                sh.BeginTrans();

                #region 添加配送企业

                string strExists = string.Format(@"SELECT *
  FROM TB_CompanyInfo inner join TB_Company on TB_Company.CompanyID=TB_CompanyInfo.CompanyID 
where TB_CompanyInfo.CompanyName='{0}' or (BusinessCertificate='{1}' and CompanyType<>0)", companyinfo.CompanyName, companyinfo.BusinessCertificate);


                result = sh.ExecuteDataSet(strExists).Tables[0].Rows.Count;
                //检验存在性
                if (result > 0)
                {
                    sh.RollTrans();
                    return 2;
                }

                string strSql = string.Empty;
                strSql = HZ.Data.DAL_Helper.GetInsertSql(companyinfo);

                result = sh.ExecuteNonQuery(strSql);

                //if (i == 1)
                //{
                //    BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog { OperateMessage = string.Format("添加企业成功(企业名称：{0})", companyinfo.CompanyName) });

                //}

                #endregion

                #region 审核通过配送企业


                IList<CompanyInfo> list = new List<CompanyInfo>();
                list.Add(companyinfo);

                // 获取最大的UserID
                System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"\d+");
                string sql = "SELECT MAX(UserID) FROM TB_USER WHERE UserID LIKE 'P%'";
                object obj = sh.ExecuteScalar(sql);
                string maxid = string.Empty;
                int id = 0;
                if (Convert.IsDBNull(obj))
                {
                    maxid = "P0001";
                }
                else
                {
                    maxid = obj.ToString();
                    id = int.Parse(regex.Match(maxid).Value);
                }
                // 获取ID
                sql = "SELECT MAX(CompanyID) FROM TB_Company Where CompanyId LIKE 'P%' ";
                obj = sh.ExecuteScalar(sql);
                string maxhospitalid = "";
                int hid = 0;

                if (Convert.IsDBNull(obj))
                {
                    maxhospitalid = "P0001";
                }
                else
                {
                    maxhospitalid = obj.ToString();
                    hid = int.Parse(regex.Match(maxhospitalid).Value);
                }
                // 插入帐号
                for (int i = 0; i < list.Count; i++)
                {
                    id++;
                    hid++;
                    // 插入
                    string companyid = "P" + hid.ToString("D4");
                    //string userid = "P" + id.ToString("D4");
                    string userid = "P" + hid.ToString("D4");
                    outUserIDs += userid + ";";
                    Model.Company company = new Company()
                    {
                        CompanyID = companyid,
                        CompanyName = list[i].CompanyName,
                        CompanyType = Model.Enum.EnumCompanyType.配送企业

                    };
                    sql = string.Format(@"INSERT INTO TB_Company
           (CompanyID,CompanyName,CompanyType) VALUES  ('{0}','{1}',{2})", companyid, list[i].CompanyName, 2);
                    //  HZ.Data.DAL_Helper.GetInsertSql(company);
                    sh.ExecuteNonQuery(sql);

                    //Model.User_Tail user = new User_Tail()
                    //{
                    //    UserID = userid,
                    //    IsAdmin = true,
                    //    IsUsing = false,
                    //    UserPassword = HZ.Fun2.GetMd5("999999"),
                    //    UserName = company.CompanyName
                    //};

                    sql = string.Format("INSERT INTO TB_User (UserID,UserName,UserPassword,IsAdmin,IsUsing) VALUES ('{0}','{1}','{2}',1,0)", userid, company.CompanyName, HZ.Fun2.GetMd5("999999"));

                    result = sh.ExecuteNonQuery(sql);
                    // 更新关联
                    sql = string.Format("UPDATE TB_CompanyInfo SET CompanyID = '{0}' WHERE CompanyName = '{1}' ", companyid, list[i].CompanyName);
                    result = sh.ExecuteNonQuery(sql);

                    // 插入用户表机构关联
                    //Model.Role_User ru = new Role_User()
                    //{
                    //    IsAdmin = true,
                    //    OrgID = companyid,
                    //    RoleID = "02",
                    //    UserID = userid
                    //};
                    sql = string.Format("INSERT INTO TB_ROLE_USER (UserID,RoleID,IsAdmin,OrgID) VALUES ('{0}','02',1,'{1}')", userid, companyid);
                    result = sh.ExecuteNonQuery(sql);

                    // 暂时不插入用户权限
                    //                    sql = string.Format(@"INSERT INTO TB_UserRule (UserID,OperatingRuleID,IsEffective)
                    //SELECT '{0}', OperatingRuleID ,1 FROM TB_Role_Rule WHERE RoleID = '02' AND IsUsing = 1", userid);
                    //                    sh.ExecuteNonQuery(sql);
                }

                #endregion

                #region 插入配送区域

                string strSqlA = string.Format(@"INSERT INTO TB_SelectArea
           (CompanyID_PS,AreaIDs) VALUES ('{0}','{1}')", outUserIDs.Split(';')[0], selectArea.AreaIDs);

                sh.ExecuteNonQuery(strSqlA);

                #endregion

                sh.CommitTrans();
                return 1;

            }
            catch (System.Data.SqlClient.SqlException ee)
            {
                sh.RollTrans();
                log4netManager.LogDebug("BLL_Company", "企业插入配送企业出现SqlException", ee);
                //return 2;
                result = 0;
            }
            if (result == 1)
            {
                BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog { OperateMessage = string.Format("生产企业注册一个新配送企业信息：{0};处理时间:{1};)", companyinfo.CompanyID, DateTime.Now.ToString()), ClientIP = HZ.Fun2.GetClientIP() });
            }
            return result;
        }


        /// <summary>
        /// 编辑企业信息
        /// </summary>
        /// <param name="company"></param>
        /// <param name="companyinfo">企业信息</param>
        /// <param name="selectArea"></param>
        /// <returns>True:成功;False:失败</returns>
        public int UpdateCompanyInfo(Company company, CompanyInfo companyinfo, Model.SelectArea selectArea)
        {
            int result = 0;
            var sh = HZ.Data.DbHelperFactory.Create();
            try
            {
                sh.BeginTrans();

                #region 编辑配送企业

                string strExists = string.Format(@"SELECT *
  FROM TB_CompanyInfo inner join TB_Company on TB_Company.CompanyID=TB_CompanyInfo.CompanyID 
where (TB_CompanyInfo.CompanyName='{0}' or (BusinessCertificate='{2}' and CompanyType<>0)) and TB_CompanyInfo.CompanyId<>'{1}' ", companyinfo.CompanyName, companyinfo.CompanyID, companyinfo.BusinessCertificate);

                result = sh.ExecuteDataSet(strExists).Tables[0].Rows.Count;
                //检验存在性
                if (result > 0)
                {
                    sh.RollTrans();
                    return 2;
                }

                if (UpdateCompany(company) == false)
                {
                    sh.RollTrans();
                    return 0;
                }

                #region 临时的
                string strSql = string.Format(@"UPDATE [TB_CompanyInfo]
   SET  [BusinessRange] = '{0}'
,[CompanyName] = '{1}'
      ,TelNo = '{2}'
      ,CellNo = '{3}'
      ,ContactPerson = '{4}'
      ,[LayMan] = '{5}'
      ,Address = '{6}'
      ,[Fax] = '{7}'
      ,[CheckStatus] = {8}
      ,[CheckPerson] = '{9}'
      ,[TotalFund] =  {10}
      ,[FixFund] =  {11}
      ,[Website] = '{12}'
      ,Email = '{13}'
      ,[IsGSP] =  {14}
      ,[GSPCode] = '{15}'
      ,[Remarks] = '{16}'
      ,[BusinessCertificate] = '{17}' ", companyinfo.BusinessRange, companyinfo.CompanyName, companyinfo.TelNo ?? "", companyinfo.CellNo ?? "", companyinfo.ContactPerson ?? "", companyinfo.LayMan ?? "", companyinfo.Address ?? "", companyinfo.Fax ?? "", companyinfo.CheckStatus ?? 0, companyinfo.CheckPerson ?? "", companyinfo.TotalFund ?? 0, companyinfo.FixFund ?? 0, companyinfo.Website, companyinfo.Email, companyinfo.IsGSP.HasValue ? (companyinfo.IsGSP.Value ? 1 : 0) : 0, companyinfo.GSPCode, companyinfo.Remarks, companyinfo.BusinessCertificate);
                if (companyinfo.CheckDate.HasValue)
                {
                    strSql += string.Format(@",[CheckDate] = '{0}'", companyinfo.CheckDate);
                }
                if (companyinfo.GSPTime.HasValue)
                {
                    strSql += string.Format(@",[GSPTime] = '{0}'", companyinfo.GSPTime);
                }
                if (companyinfo.BusinessCertificateDate.HasValue)
                {
                    strSql += string.Format(@",[BusinessCertificateDate] ='{0}'", companyinfo.BusinessCertificateDate);
                }
                strSql += string.Format(@" WHERE [CompanyID] = '{0}'", companyinfo.CompanyID);
                #endregion

                strSql = HZ.Data.DAL_Helper.GetUpdateSql(companyinfo);

                result = sh.ExecuteNonQuery(strSql);

                #endregion

                #region 更改配送区域

                string strSqlA = string.Format(@"UPDATE TB_SelectArea
   SET AreaIDs ='{0}'
 WHERE CompanyID_PS = '{1}'", selectArea.AreaIDs, selectArea.CompanyID_PS);

                sh.ExecuteNonQuery(strSqlA);

                #endregion

                sh.CommitTrans();
                return 1;

            }
            catch (System.Data.SqlClient.SqlException ee)
            {
                sh.RollTrans();
                log4netManager.LogDebug("BLL_Company", "企业更改配送企业出现SqlException", ee);
                result = 0;
            }
            if (result == 1)
            {
                BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog { OperateMessage = string.Format("编辑企业信息：{0};处理时间:{1};)", companyinfo.CompanyID, DateTime.Now.ToString()), ClientIP = HZ.Fun2.GetClientIP() });
            }
            return result;
        }

        /// <summary>
        /// 将系统帐户与企业信息进行关联
        /// </summary>
        /// <param name="companyinfo"></param>
        /// <param name="?"></param>
        /// <returns></returns>
        public int MarkLinkToCompanyInfo(Model.CompanyInfo companyinfo, Model.Company company)
        {
            ThrowHelper.Throw(companyinfo.CompanyName != null);
            ThrowHelper.Throw(company.CompanyID != null);
            int state = DAL.DAL_Company.MarkLinkToCompanyInfo(companyinfo, company);
            if(state == 1)
            {
                BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog { OperateMessage = string.Format("将系统帐户与企业信息进行关联：{0};处理时间:{1};)", companyinfo.CompanyID, DateTime.Now.ToString()), ClientIP = HZ.Fun2.GetClientIP() });
            }
            return state;
        }
        /// <summary>
        /// 获取未注册的企业
        /// </summary>
        /// <param name="where"></param>
        /// <param name="currentpage"></param>
        /// <param name="pagesize"></param>
        /// <param name="totalrecord"></param>
        /// <returns></returns>
        public IList<CompanyInfo> GetUnregedCompanyInfo(Model.Query.CompanyInfo where, int currentpage, int pagesize, out int totalrecord)
        {

            return DAL_Company.GetUnregedCompanyInfo(where, currentpage, pagesize, out totalrecord);
            throw new NotImplementedException();
        }

        /// <summary>
        /// 批量审核未注册企业
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public int AduitCompany(IList<CompanyInfo> list, out string outUserids)
        {
            int state = DAL_Company.AduitCompany(list, out outUserids);
            if(state == 1)
            {
                BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog { OperateMessage = string.Format("批量审核未注册企业：{0};处理时间:{1};)", outUserids, DateTime.Now.ToString()), ClientIP = HZ.Fun2.GetClientIP() });
            }
            return state;
        }

        /// <summary>
        /// 删除不需要的企业列表
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public int DeleteCompanyInfo(IList<Model.CompanyInfo> list)
        {
            int state =  DAL.DAL_Company.DeleteCompanyInfo(list);
            if(state == 1)
            {
                BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog { OperateMessage = string.Format("删除不需要的企业列表;处理时间:{0};)", DateTime.Now.ToString()), ClientIP = HZ.Fun2.GetClientIP() });
            }
            return state;
        }

        /// <summary>
        /// 更新企业信息(企业名除外)
        /// </summary>
        /// <param name="companyinfo">企业名不能空</param>
        /// <returns></returns>
        public int UpdateCompanyInfo(Model.CompanyInfo companyinfo)
        {
            int state = HZ.Data.DAL_Helper.OperateTableSQL(companyinfo, HZ.Data.TableOperator.Update);
            if(state == 1)
            {
                BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog { OperateMessage = string.Format("更新企业信息(企业名除外)：{0};处理时间:{1};)", companyinfo.CompanyID, DateTime.Now.ToString()), ClientIP = HZ.Fun2.GetClientIP() });
            }
            return state;
        }

        /// <summary>
        /// 根据企业ID获取企业其它信息
        /// </summary>
        /// <param name="companyid"></param>
        /// <returns></returns>
        public CompanyInfo GetCompanyInfoByID(string companyid)
        {
            return DAL.DAL_Company.GetCompanyInfoByID(companyid);
        }

        /// <summary>
        /// 获取可配送某地区的配送企业
        /// 
        /// </summary>
        /// <param name="where"></param>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalRecord"></param>
        /// <returns></returns>
        public IList<Model.View.CompanyDistributableArea> GetDistributableCompany(Model.Query.CompanyDistributableArea where, int currentPage, int pageSize, out int totalRecord)
        {
            ThrowHelper.Throw(!string.IsNullOrEmpty(where.AreaID), "请提供地区参数！");
            return HZ.DrugTrade.DAL2.DAL_Helper.GetPagedView<Model.View.CompanyDistributableArea, Model.Query.CompanyDistributableArea>(where, currentPage, pageSize, out  totalRecord);
        }
        #endregion


        /// <summary>
        /// 企业信息
        /// </summary>
        /// <param name="strWhere"></param>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalRecord"></param>
        /// <returns></returns>
        public DataTable GetCompanyInfoByWhere(string strWhere, int currentPage, int pageSize, out int totalRecord)
        {
            StringBuilder sql = new StringBuilder();
            sql.Append(string.Format(@"SELECT TB_CompanyInfo.*,TB_Company.companytype,case tb_company.companytype when 2 then '配送企业' when 3 then '生产企业直接配送' end as companytypes
  FROM TB_CompanyInfo inner join TB_Company
on TB_Company.companyid=TB_CompanyInfo.companyid  
where ((companytype<>0 and companytype<>1) or TB_Company.companyid in ('J0156','J0587','J0604')) {0} ", strWhere));
            HZ.Data.PageDescribe des = new HZ.Data.PageDescribe(sql.ToString(), pageSize);
            des.CurrentPage = currentPage;
            totalRecord = des.TotalCount;
            return des.GetSpecailPage();
        }
        /// <summary>
        /// 投标企业信息 add by zdc
        /// </summary>
        /// <param name="strWhere"></param>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalRecord"></param>
        /// <returns></returns>
        public DataTable GetCompanySCInfoByWhere(string strWhere, int currentPage, int pageSize, out int totalRecord)
        {
            StringBuilder sql = new StringBuilder();
            sql.Append(string.Format(@"SELECT TB_CompanyInfo.*,TB_Company.companytype
  FROM TB_CompanyInfo inner join TB_Company
on TB_Company.companyid=TB_CompanyInfo.companyid  
where ((companytype=0 or companytype=1) and TB_Company.companyid not in ('J0156','J0587','J0604')) {0} ", strWhere));
            HZ.Data.PageDescribe des = new HZ.Data.PageDescribe(sql.ToString(), pageSize);
            des.CurrentPage = currentPage;
            totalRecord = des.TotalCount;
            return des.GetSpecailPage();
        }
        /// <summary>
        /// 判断是否是生产企业 add by zdc
        /// </summary>
        /// <param name="companyID"></param>
        /// <returns></returns>
        public bool IsSCCompany(string companyID)
        {
            bool flag = false;
            string sqlInfo = @"SELECT count(*)
                  FROM TB_CompanyInfo inner join TB_Company
                on TB_Company.companyid=TB_CompanyInfo.companyid  
                where ((companytype=0 or companytype=1) and TB_Company.companyid not in ('J0156','J0587','J0604'))
                and TB_CompanyInfo.Companyid='"+companyID+"'";
            object count = HZ.Data.DbHelperFactory.Create().ExecuteScalar(sqlInfo);
            if (count!=null)
            {
                if (int.Parse(count.ToString())>0)
                {
                    flag = true;
                }
            }
            return flag;
        }
        /// <summary>
        /// 获取要发放密码的企业列表 add by zdc
        /// </summary>
        /// <param name="strWhere"></param>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalRecord"></param>
        /// <returns></returns>
        public IList<Model.View.CompanySendPwd> GetCompanySendByWhere(string strWhere, int currentPage, int pageSize, out int totalRecord)
        {
            return DAL_Company.GetCompanySendByWhere(strWhere, currentPage, pageSize, out totalRecord);
        }
        /// <summary>
        /// 获取企业用户信息 add by zdc
        /// </summary>
        /// <param name="comId"></param>
        /// <returns></returns>
        public Model.View.CompanySendPwd GetCom(string comId)
        {
            //Model.View.CompanySendPwd csp = new HZ.DrugTrade.Model.View.CompanySendPwd();
            //csp.CompanyId = comId;
            //csp.IsSend = int.Parse(HZ.Data.DbHelperFactory.Create().ExecuteScalar("select issend from tb_companysendpwd where userid='" + comId + "'").ToString());
            //return HZ.Data.DAL_Helper.GetPagedModel<Model.View.CompanySendPwd, Model.Query.CompanySendPwd>(csp, 1, 0, out totalrecord)[0];
            return DAL_Company.GetCom(comId);
        }
        /// <summary>
        /// 发放企业用户密码 add by zdc
        /// </summary>
        /// <param name="ComAccountPwd">企业用户</param>
        /// <param name="outComAccountPwd">企业用户</param>
        /// <returns>0.失败；1成功</returns>
        public int SendComAccountPWD(Model.View.CompanySendPwd companySendPwd, out Model.View.CompanySendPwd outCompanySendPwd)
        {
            int result =DAL_Company.SendComAccountPWD(companySendPwd, out outCompanySendPwd);
            if (result==1) {
                BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog() { OperateMessage = string.Format("给{0}企业发放密码", companySendPwd.CompanyName) }); 
            }
            return result;
        }
        /// <summary>
        /// 企业信息
        /// </summary>
        /// <param name="strWhere"></param>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalRecord"></param>
        /// <returns></returns>
        public DataTable GetCompanyInfoByWhereForMerge(string strWhere, int currentPage, int pageSize, out int totalRecord)
        {
            StringBuilder sql = new StringBuilder();
            sql.Append(string.Format(@"SELECT TB_CompanyInfo.*,TB_Company.companytype
  FROM TB_CompanyInfo inner join TB_Company 
on TB_Company.companyid=TB_CompanyInfo.companyid  
inner  join TB_user 
on TB_user.userid=TB_CompanyInfo.companyid
where companytype<>0 {0} ", strWhere));
            HZ.Data.PageDescribe des = new HZ.Data.PageDescribe(sql.ToString(), pageSize);
            des.CurrentPage = currentPage;
            totalRecord = des.TotalCount;
            return des.GetSpecailPage();
        }

        /// <summary>
        /// 企业信息:含可配送区域
        /// </summary>
        /// <param name="strWhere"></param>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalRecord"></param>
        /// <returns></returns>
        public DataTable GetCompanyInfoByWhere2(string strWhere, int currentPage, int pageSize, out int totalRecord)
        {
            StringBuilder sql = new StringBuilder();
            sql.Append(string.Format(@"SELECT TB_CompanyInfo.*,TB_Company.companytype,TB_SelectArea.AreaIDs,aa.companyName  companyName_Add
  FROM TB_CompanyInfo inner join TB_Company 
on TB_Company.companyid=TB_CompanyInfo.companyid  
left join  TB_SelectArea on TB_SelectArea.CompanyID_PS=TB_CompanyInfo.companyid  
left join  TB_CompanyInfo as aa on  aa.CompanyID=TB_CompanyInfo.Addpersonid  
where companytype<>0 {0} ", strWhere));
            HZ.Data.PageDescribe des = new HZ.Data.PageDescribe(sql.ToString(), pageSize);
            des.CurrentPage = currentPage;
            totalRecord = des.TotalCount;
            return des.GetSpecailPage();
        }
        /// <summary>
        /// 企业信息:含可配送区域 修改 by zdc
        /// </summary>
        /// <param name="strWhere"></param>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalRecord"></param>
        /// <returns></returns>
        public DataTable GetCompanyInfoByWhereZDC(string strWhere, int currentPage, int pageSize, out int totalRecord)
        {
            StringBuilder sql = new StringBuilder();
            sql.Append(string.Format(@"SELECT TB_CompanyInfo.*,TB_Company.companytype, aa.companyName companyName_Add,tb_company.ishcygcg
  FROM TB_CompanyInfo inner join TB_Company 
on TB_Company.companyid=TB_CompanyInfo.companyid   
left join  TB_CompanyInfo  aa on  aa.CompanyID=TB_CompanyInfo.Addpersonid  
where companytype<>0 {0} ", strWhere));
            HZ.Data.PageDescribe des = new HZ.Data.PageDescribe(sql.ToString(), pageSize);
            des.CurrentPage = currentPage;
            totalRecord = des.TotalCount;
            return des.GetSpecailPage();
        }

        /// <summary>
        /// 企业信息:含可配送区域
        /// </summary>
        /// <returns></returns>
        public DataTable GetCompanyInfoByWhere3(string strWhere, int currentPage, int pageSize, out int totalRecord)
        {
            BLL_UserSession.CheckSession();
            return DAL_Company.GetCompanyInfoByWhere3(strWhere, currentPage, pageSize, out totalRecord);
        }


        /// <summary>
        /// 合并企业信息
        /// </summary>
        /// <returns></returns>
        public int MergeCompanyInfo(string standardID, string mergeID)
        {
            int result = 0;
            var sh = HZ.Data.DbHelperFactory.Create();
            try
            {
                sh.BeginTrans();

                string strSql = string.Empty;


                #region 可配送区域合并

                strSql = string.Format(@"update  standard set standard.AreaIDs=NVL(standard.AreaIDs,'')+','+NVL(merge.AreaIDs,'') from TB_SelectArea merge,TB_SelectArea standard where merge.CompanyID_PS='{0}' and standard.CompanyID_PS='{1}'", mergeID, standardID);

                sh.ExecuteNonQuery(strSql);

                #endregion

                #region 配送关系合并

                strSql = string.Format(@"update  merg set merg.CompanyID_PS='{1}' 
from TB_SelectRelation merg 
where  merg.ProcureCatalogID+merg.AreaID not in (select stand.ProcureCatalogID +stand.AreaID 
from  TB_SelectRelation stand 
where  stand.CompanyID_PS='{1}'  )
and  merg.CompanyID_PS='{0}'", mergeID, standardID);
                sh.ExecuteNonQuery(strSql);



                strSql = string.Format(@"update  merg set merg.CompanyID_PS='{1}' 
from TB_AreaDistribution merg 
where  merg.ProcureCatalogID+merg.AreaID not in (select stand.ProcureCatalogID +stand.AreaID 
from  TB_AreaDistribution stand 
where  stand.CompanyID_PS='{1}'  )
and  merg.CompanyID_PS='{0}'", mergeID, standardID);
                sh.ExecuteNonQuery(strSql);

                #endregion

                #region 删除要合并的企业信息(暂时)

                strSql = string.Format(@"delete from TB_Role_User  where UserID='{0}'", mergeID);
                strSql += string.Format(@";delete from TB_UserRule  where UserID='{0}'", mergeID);
                strSql += string.Format(@";delete from TB_User  where UserID='{0}'", mergeID);
                strSql += string.Format(@";delete from TB_SelectArea  where CompanyID_PS='{0}'", mergeID);
                strSql += string.Format(@";delete from TB_SelectRelation  where CompanyID_PS='{0}'", mergeID);
                strSql += string.Format(@";delete from TB_AreaDistribution  where CompanyID_PS='{0}'", mergeID);
                strSql += string.Format(@";delete from TB_CompanyInfo  where CompanyID='{0}'", mergeID);
                strSql += string.Format(@";delete from TB_Company  where CompanyID='{0}'", mergeID);

                sh.ExecuteNonQuery(strSql);

                #endregion

                sh.CommitTrans();
                return 1;

            }
            catch (Exception ee)
            {
                sh.RollTrans();
                log4netManager.LogDebug("BLL_Company", "合并企业信息SqlException", ee);
                result = 0;
            }
            return result;
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="selectRelation"></param>
        /// <returns></returns>
        public int UpdateCompanySNKEY(IList<Model.Company> lst, string UID)
        {
            BLL_UserSession.CheckSession();
            string strIDS = string.Empty;
            string strSType = string.Empty;
            foreach (Model.Company item in lst)
            {
                strIDS += item.CompanyID + ";";
                strSType = item.SNKEY;
            }
            BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog { OperateMessage = string.Format("投标企业锁定处理：{0}；状态:{1};处理人：{2};处理时间：{3};)", strIDS, strSType, UID, DateTime.Now.ToString()),ClientIP=HZ.Fun2.GetClientIP() });
            return DAL.DAL_Company.UpdateCompanySNKEY(lst);
        }

        /// <summary>
        /// 获取所有企业
        /// </summary>
        /// <returns>所有企业</returns>
        public IList<Company> GetCompanyByWhere(string strWhere)
        {
            BLL_UserSession.CheckSession();
            return DAL_Company.GetCompanyByWhere(strWhere);
        }
        /// <summary>
        /// 中心审核配送企业的配送区域 zdc
        /// </summary>
        /// <param name="ps"></param>
        /// <param name="checkUser">审核人</param>
        /// <param name="areaIDs">审核区域</param>
        /// <param name="checkType">0:审核未通过，否则通过</param>
        /// <returns></returns>
        public bool CheckAreaByZbzx(PSSelectArea ps, string checkUser, string areaIDs, int checkType)
        {
            bool state = DAL_Company.CheckAreaByZbzx(ps, checkUser, areaIDs, checkType);
            if(state == true)
            {
                BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog { OperateMessage = string.Format("中心审核配送企业的配送区域：{0};处理时间:{1};)", ps.CompanyPS_Id, DateTime.Now.ToString()), ClientIP = HZ.Fun2.GetClientIP() });
            }
            return state;
        }
        /// <summary>
        /// 审核配送企业的详细信息 zdc
        /// </summary>
        /// <param name="ps"></param>
        /// <param name="checkType"></param>
        /// <param name="checkUser"></param>
        /// <returns></returns>
        public bool CheckCompanyInfo(PSSelectArea ps, int checkType, string checkUser, string state)
        {
            bool states = DAL_Company.CheckCompanyInfo(ps, checkType, checkUser, state);
            if (states== true)
            {
                BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog { OperateMessage = string.Format("审核配送企业的详细信息：{0};处理时间:{1};)", ps.CompanyPS_Id, DateTime.Now.ToString()), ClientIP = HZ.Fun2.GetClientIP() });
            }
            return states;
        }
        /// <summary>
        /// 审核配送企业和配送区域的权利 zdc
        /// </summary>
        /// <param name="ps"></param>
        /// <param name="checkType"></param>
        /// <param name="checkUser"></param>
        /// <returns></returns>
        public bool CheckEnterpriseInfo(PSSelectArea ps, int checkType, string checkUser)
        {
            bool state = DAL_Company.CheckEnterpriseInfo(ps, checkType, checkUser);
            if(state == true)
            {
                BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog { OperateMessage = string.Format("审核配送企业和配送区域的权利：{0};处理时间:{1};)", ps.CompanyPS_Id, DateTime.Now.ToString()), ClientIP = HZ.Fun2.GetClientIP() });
            }
            return state;
        }
        /// <summary>
        /// 获取配送企业选择已提交的配送区域 zdc 
        /// </summary>
        /// <param name="comPS_Id"></param>
        /// <returns></returns>
        public DataTable GetAreasById(string comPS_Id)
        {
            return DAL_Company.GetAreasById(comPS_Id);
        }
        /// <summary>
        /// 获取配送企业选择的配送区域 zdc 
        /// </summary>
        /// <param name="comPS_Id"></param>
        /// <returns></returns>
        public string GetAreasByComId(string comPS_Id)
        {
            return DAL_Company.GetAreasByComId(comPS_Id);
        }
        /// <summary>
        /// 获取配送企业的类型 zdc
        /// </summary>
        /// <param name="comPS_Id"></param>
        /// <returns></returns>
        public string GetCompanyType(string comPS_Id)
        {
            return DAL_Company.GetCompanyType(comPS_Id);
        }
        /// <summary>
        /// 配送企业查看审核原因 zdc
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="areaId"></param>
        /// <returns></returns>
        public string GetReason(string userId, string areaId)
        {
            return DAL_Company.GetReason(userId, areaId);
        }

        /// <summary>
        /// 获取企业类型 add zdc
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public string GetComType(string userId)
        {
            return DAL_Company.GetComType(userId);
        }

        /// <summary>
        /// 获取所有国内生产企业和配送企业信息由生产企业勾选用
        /// </summary>
        /// <returns></returns>
        public DataTable GetCompanyInfo()
        {
            return DAL_Company.GetCompanyInfo();
        }
        /// <summary>
        /// 返回公司的文件过期情况
        /// </summary>
        /// <param name="companyid">公司ID</param>
        /// <param name="type">公司类型</param>
        /// <returns></returns>
        public DataTable GetCmpTimeinfo(string companyid,string compnayname)
        {
            return DAL_Company.GetCmpTimeinfo(companyid, compnayname);
        }

        /// <summary>
        /// 分页先是企业信息 add by gaoyang
        /// </summary>
        /// <param name="companyid">企业流水号</param>
        /// <param name="companyname">企业名称</param>
        /// <param name="currentPage">当前是第几页</param>
        /// <param name="pageSize">每页显示的条目数</param>
        /// <param name="totalRecord">一共分多少页</param>
        /// <returns></returns>
        public IList<Model.View.VCompanyInfo> GetCmpTimeinfoByWhere(string companyid, string companyname, int currentPage, int pageSize, out int totalRecord)
        {
            return DAL_Company.GetCmpTimeinfoByWhere(companyid, companyname, currentPage, pageSize, out totalRecord);
        }

        /// <summary>
        /// 根据企业类型得到一共有多少条数据
        /// </summary>
        /// <param name="roleId">tb_role_user表的roleId用来判断用户类型</param>
        //public int GetCompanyCount(string roleId)
        //{
        //    return DAL_Company.GetCompanyCount(roleId);
        //}
        /// <summary>
        /// 盟市查询企业信息
        /// add by Meng 2013-03-12
        /// </summary>
        /// <param name="strWhere"></param>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalRecord"></param>
        /// <returns></returns>
        public DataTable GetUnionCityCompanyInfoByWhere(string strWhere, int currentPage, int pageSize, out int totalRecord)
        {
            StringBuilder sql = new StringBuilder();
            sql.Append(string.Format(@"SELECT * from VIEW_AreaCompany where 1=1 {0} ", strWhere));
            HZ.Data.PageDescribe des = new HZ.Data.PageDescribe(sql.ToString(), pageSize);
            des.CurrentPage = currentPage;
            totalRecord = des.TotalCount;
            return des.GetSpecailPage();
        }
        /// 中心查询盟市审核配送企业信息
        /// add by Meng 2013-03-12
        /// </summary>
        /// <param name="strWhere"></param>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalRecord"></param>
        /// <returns></returns>
        public DataTable GetUnionCityCompanyInfoBySelect(string strWhere, int currentPage, int pageSize, out int totalRecord)
        {
            StringBuilder sql = new StringBuilder();
            sql.Append(string.Format(@"SELECT a.*,b.areaname from VIEW_AreaCompany a left join tb_area b on a.areaid = b.areaid where 1=1 and companyid = '{0}' ", strWhere));
            HZ.Data.PageDescribe des = new HZ.Data.PageDescribe(sql.ToString(), pageSize);
            des.CurrentPage = currentPage;
            totalRecord = des.TotalCount;
            return des.GetSpecailPage();
        }
         /// <summary>
        /// 更新企业信息
        /// add by Meng 2013-03-20
        /// </summary>
        /// <param name="companyinfo"></param>
        /// <returns></returns>
        public int UpdateCompanyInfoByCompanyId(HZ.DrugTrade.Model.CompanyInfo companyinfo)
        {
            int state = DAL_Company.UpdateCompanyInfoByCompanyId(companyinfo);
            if(state == 1)
            {
                BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog { OperateMessage = string.Format("更新企业信息：{0};处理时间:{1};)", companyinfo.CompanyID, DateTime.Now.ToString()), ClientIP = HZ.Fun2.GetClientIP() });
            }
            return state;
        }
    }
}
